import { loginByUsername, logout, getUserInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
// import { Get as GetProjects } from '@/api/erp/elicink/project'
import Cookies from 'js-cookie'

const user = {
  state: {
    user: '',
    status: '',
    code: '',
    token: getToken(),
    name: '',
    fullname: '',
    avatar: '',
    introduction: '',
    roles: [],
    projectId: Cookies.get('cms_project_id__search') || null, // 从 Cookie 初始化项目 ID
    projects: null,
    ai_task_api_key: null, // AI任务API密钥
    setting: {
      articlePlatform: []
    }
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_FULLNAME: (state, fullname) => {
      console.log('SETFULLNAME', fullname)
      state.fullname = fullname
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    // 设置项目 ID
    SET_PROJECT_ID(state, projectId) {
      state.projectId = projectId
      Cookies.set('cms_project_id__search', projectId, { expires: 7 }) // 同时更新 Cookie
      console.log('Set project ID and save', projectId)
    },
    SET_PROJECTS(state, projects) {
      state.projects = projects
      console.log('set projects!!!')
      Cookies.set('projects', JSON.stringify(projects), { expires: 7 })
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password).then(response => {
          const data = response.data
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserInfo(state.token).then(response => {
          if (!response.data) { // 由于mockjs 不支持自定义状态码只能这样hack
            reject('error')
          }
          const data = response.data
          if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', data.roles)
          } else {
            reject('getInfo: roles must be a non-null array !')
          }

          commit('SET_NAME', data.name)
          commit('SET_FULLNAME', data.fullname)
          commit('SET_AVATAR', data.avatar || 'w')
          commit('SET_INTRODUCTION', data.introduction || '懒人')
          state.projectId = Cookies.get('cms_project_id__search')
          console.log('Get Project ID form Cookies', state.projectId)
          if (data.projects && data.projects.length > 0) {
            if (!state.projectId) {
              console.log('set project id to default')
              commit('SET_PROJECT_ID', data.projects[0].id.toString())
            } else {
              if (!data.projects.some(project => project.id.toString() === state.projectId.toString())) {
                console.log('Set project id to defult')
                commit('SET_PROJECT_ID', data.projects[0].id.toString())
              }
            }
            data.projects.forEach(project => {
              project.id = project.id.toString()
            })
            console.log('保存设置')
            commit('SET_PROJECTS', data.projects)
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 第三方验证登录
    // LoginByThirdparty({ commit, state }, code) {
    //   return new Promise((resolve, reject) => {
    //     commit('SET_CODE', code)
    //     loginByThirdparty(state.status, state.email, state.code).then(response => {
    //       commit('SET_TOKEN', response.data.token)
    //       setToken(response.data.token)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

    // 动态修改权限
    ChangeRoles({ commit }, role) {
      return new Promise(resolve => {
        commit('SET_TOKEN', role)
        setToken(role)
        getUserInfo(role).then(response => {
          const data = response.data
          commit('SET_ROLES', data.roles)
          commit('SET_NAME', data.name)
          commit('SET_FULLNAME', data.fullname)
          commit('SET_AVATAR', data.avatar)
          commit('SET_INTRODUCTION', data.introduction)
          resolve()
        })
      })
    },
    // 提交 mutation 来更改项目 ID
    setProjectId({ commit }, projectId) {
      commit('SET_PROJECT_ID', projectId)
    },
    // async fetchProjects({ commit, state }) {
    //   if (!state.projects) {
    //     const response = await GetProjects();
    //     const projects = response.data.data
    //     if (!this.state.projectId && projects.length) {
    //       commit('SET_PROJECT_ID', projects[0].id.toString());
    //     }
    //     if (projects && projects.length) {
    //       projects.forEach(project => {
    //         project.id = project.id.toString();
    //       });
    //     }
    //     commit('SET_PROJECTS', projects);
    //   }
    // },
    getProjectsFromCookies({ commit }) {
      const projectsInCookie = Cookies.get('projects')
      if (projectsInCookie) {
        commit('SET_PROJECTS', JSON.parse(projectsInCookie))
      }
    },
    initializeProjects({ commit }) {
      const projectsInCookie = Cookies.get('projects')
      if (projectsInCookie) {
        commit('SET_PROJECTS', JSON.parse(projectsInCookie))
      } else {
        // 如果 Cookie 中没有项目数据，则触发 API 请求
        console.log('获取项目情况')
        this.dispatch('fetchProjects')
      }
    }
  }
}

export default user
